package com.xudow.app.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;

import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.xudow.app.Config;
import com.xudow.app.XApplication;
import com.xudow.app.ui.widget.LoadingDialog;
import com.xudow.app.util.Lists;

import java.util.List;

/**
 * A base activity that handles common functionality in the app.
 *
 * @author lukcheng
 */
public abstract class BaseActivity extends AppCompatActivity {
    private LoadingDialog _loadingDialog;
    protected XApplication application;
    public XApplication getMyApp(){
        return application;
    }
    /**
     * Activity里面运行的Task，退出Activity时候必须停止掉
     */
    private List<AsyncTask> tasksInActivity = Lists.newArrayList();

    /**
     * 是否注册退出广播
     */
    private boolean isRegisterExitBroadcast = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        application = (XApplication) getApplication();
        if (isNeedLogin()) {
            if (!application.isLogin()) {
                startActivity(new Intent(this, LoginActivity.class));
            }
        }
        PushAgent.getInstance(this).onAppStart();
    }


    @Override
    protected void onResume() {
        super.onResume();

        //友盟统计
        MobclickAgent.onResume(this);

        if (getIntent().getBooleanExtra("registerExitBroadcast", true)) {
            isRegisterExitBroadcast = true;

            IntentFilter filter = new IntentFilter();
            filter.addAction(Config.EXIT_BROADCAST_ACTION);
            registerReceiver(exitBroadcastReceiver, filter);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        //友盟统计
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        if (isRegisterExitBroadcast) {
            try {
                unregisterReceiver(this.exitBroadcastReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        closeAllRunningTasks();

        super.onDestroy();
    }

    /**
     * 显示加载对话框
     *
     * @param message
     */
    public void showLodingDialog(String message) {
        if (null != _loadingDialog) {
            return;
        }

        _loadingDialog = new LoadingDialog(this, message);
        _loadingDialog.setCancelable(true);
        _loadingDialog.setCanceledOnTouchOutside(false);
        _loadingDialog.show();
    }

    /**
     * 隐藏登录对话框
     */
    public void hideLoadingDialog() {
        if (null != _loadingDialog && _loadingDialog.isShowing()) {
            _loadingDialog.dismiss();
            _loadingDialog = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            closeAllRunningTasks();
            hideLoadingDialog();
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 判断是否要登录
     *
     * @return
     */
    public boolean isNeedLogin() {
        return false;
    }

    /**
     * 退出BroadcastReceiver
     */
    protected BroadcastReceiver exitBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            unregisterReceiver(this);
            ((Activity) context).finish();
        }
    };

    /**
     * 发送退出广播
     */
    public void sendExitBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Config.EXIT_BROADCAST_ACTION);
        sendBroadcast(intent);
    }

    /**
     * 关闭所有正在运行中的Task
     */
    private void closeAllRunningTasks() {
        for (AsyncTask task : tasksInActivity) {
            if (null != task && !task.isCancelled()) {
                task.cancel(true);
            }
        }
    }

    public void addTask(AsyncTask task) {
        tasksInActivity.add(task);
    }

}
